/**
 * Created by ziyu on 17/3/30px.
 */
import React from 'react'
import moment from 'moment'
import {Button, Col, DatePicker, Form, Input, message, Modal, Pagination, Popconfirm, Row, Table} from 'antd'
import Search from '../../common/components/Search'
import searchStyle from '../../common/less/search.less'
import {exportFile, fetchPost} from '../../../utils/request'
import Styles from './index.less'
import DlButton from "../../common/components/download/DlButton";

const PAGE_SIZE = 10
const {Column, ColumnGroup} = Table
const FormItem = Form.Item

class Paid extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      paidCapital: '',
      discountCapital: '',
      list: [],
      repaymentInfo: {},
      visible: false,
      buttonHidden: false,
      params: {
        paidStatus: '',
        lowerReceivedDate: moment().subtract('days', 1).format('YYYY-MM-DD'),
        findtype: '',
        inputValue: '',
        upperReceivedDate: moment().subtract('days', 1).format('YYYY-MM-DD'),
        orderType: '0'
      },
      page: {
        currentPage: 1,
        pageSize: PAGE_SIZE,
        totalCount: 0
      },
      searchParams: {
        list: [
          {
            name: 'Loan Disbursed Date',
            type: 'range',
            key: ['lowerReceivedDate', 'upperReceivedDate'],
            className: 'pr20',
            placeHolder: '',
            values: [
              moment().subtract('days', 1),
              moment().subtract('days', 1)
            ]
          },
          {
            name: 'Order status',
            type: 'select',
            key: 'orderType',
            className: 'pr20',
            values: [
              {value: '0', name: 'Unpaid'},
              {value: '1', name: 'Paid'},
              {value: '-1', name: 'All'}
            ]
          },
          {
            name: 'Filter',
            type: 'group',
            key: ['findtype', 'inputValue'],
            className: 'pr20',
            values: [{value: '', name: 'Please select '}]
          },
          {
            name: 'Paid through',
            type: 'select',
            key: 'payChannelCode',
            className: 'pr20',
            values: [{value: '', name: 'Please Select'}]
          },
          {
            name: 'Fund Account',
            type: 'select',
            key: 'fundCode',
            className: 'pr20',
            values: [{value: '', name: 'Please Select'}]
          },
          {
            name: 'Planned repayment time',
            type: 'range',
            key: ['lowerPlannedRepaymentDate', 'upperPlannedRepaymentDate'],
            className: 'pr20',
            placeHolder: '',
            values: [
              '',
              ''
            ]
          },
          {
            name: 'Actual repayment time',
            type: 'range',
            key: ['lowerActualRepaymentDate', 'upperActualRepaymentDate'],
            className: 'pr20',
            placeHolder: '',
            values: [
              '',
              ''
            ]
          },
          {
            name: 'Operate time',
            type: 'range',
            key: ['lowerOperatingTime', 'upperOperatingTime'],
            className: 'pr20',
            placeHolder: '',
            values: [
              '',
              ''
            ]
          },
          {
            name: '',
            type: 'search',
            key: '',
            className: 'pr20',
            value: []
          }
        ],
        api: '/finance/query',
        loading: true,
        downloadParams: {}
      }
    }
  }

  componentDidMount() {
    this.getData()
  }

  getData() {
    this.setState({
      loading: true
    });
    let self = this;
    let copyState = {}
    for (let i in this.state.params) {
      if (this.state.params[i] != '') {
        copyState[i] = this.state.params[i]
      }
    }
    if (!copyState.lowerReceivedDate) {
      copyState.lowerReceivedDate = moment().subtract('days', 1).format('YYYY-MM-DD')
    }
    if (!copyState.upperReceivedDate) {
      copyState.upperReceivedDate = moment().subtract('days', 1).format('YYYY-MM-DD')
    }
    if (!copyState.orderType) {
      copyState.orderType = '0'
    }
    this.setState({
      downloadParams: copyState
    });

    function GetList() {
      return new Promise((resolve, reject) => {
        fetchPost(`/finance/paid/list?currentPage=${self.state.page.currentPage}&pageSize=${self.state.page.pageSize}`, copyState).then((res) => {
          if (res.code === 0) {
            resolve(res)
          } else {
            message.error(res.msg)
            reject(res)
          }
        })
      })

    }

    Promise.all([GetList()]).then((res) => {
      let list = res[0]
      if (list.data.tradeBillAccountingList.length > 0) {
        this.setState({
          list: list.data.tradeBillAccountingList,
          page: list.data.page,
          loading: false
        })
      } else {
        this.setState({
          list: [],
          loading: false
        })
      }
    }, () => {
      this.setState({
        list: [],
        loading: false
      })
    })

  }

  nextpage(current) {
    this.setState({
      page: {
        ...this.state.page,
        currentPage: current,
        pageSize: PAGE_SIZE,
      }
    }, () => {
      this.getData()
    })
  }

  confirmPay(record, type, index) {
    this.state.list[index].disabled = true
    this.setState({
      list: this.state.list
    })

    if (type === 'lianlian') {
      fetchPost(`/pay/${record.id}/lianlianPaid`).then((res) => {
        if (res.code === 0) {
          this.getData()
        } else {
          message.error(res.msg)
          this.getData()
        }
      })
    } else if (type === 'koudai') {
      fetchPost(`/pay/${record.id}/koudayPaid`).then((res) => {
        if (res.code === 0) {
          this.getData()
        } else {
          message.error(res.msg)
          this.getData()
        }
      })
    }
  }

  changeParams(params) {
    this.setState({
      params,
      page: {
        currentPage: 1,
        pageSize: PAGE_SIZE,
        totalCount: 0
      }
    }, () => {
      this.getData()
    })
  }

  billRender(val, row, index) {
    const obj = {
      children: val,
      props: {}
    }
    if (row.billRepetedCount > 0) {
      obj.props.rowSpan = row.billRepetedCount
    } else {
      obj.props.rowSpan = 0
    }
    return obj
  }

  tradeRender(val, row, index) {
    const obj = {
      children: val,
      props: {}
    }
    if (row.tradeRepetedCount > 0) {
      obj.props.rowSpan = row.tradeRepetedCount
    } else {
      obj.props.rowSpan = 0
    }
    return obj
  }

  repayRender(val, row, index) {
    console.log(val)
    console.log(row)
    console.log(index)
    if (val === true) {
      return 'Yes'
    } else {
      return 'No'
    }
  }

  rowClass(record, index) {
    if (record.tradeIndex % 2 === 0) {
      console.log('单')
      return (Styles.double)
    } else {
      console.log('双')
      return ('')
    }
  }

  cancelExport = (e) => {
    //message.info("cancel");
  }

  //查询详情
  renderRepaymentButton(record) {
    let text = 'repayment'
    if (record.actualRepaymentTime) {
      text = 'details'
    }
    return (<div>
      <Button type="primary" onClick={() => this.getPaybackItem(record)}>{text}</Button>
    </div>)
  }

  getPaybackItem(record, time) {
    let url = null
    if (record) {
      this.state.currentTradeNo = record.orderId
      url = `/liquidation/v2/${this.state.currentTradeNo}/repayment/info?acceptNo=${record.gatewaySerialNumber}`
    } else {
      url = `/liquidation/v2/${this.state.currentTradeNo}/repayment/info?paymentDt=${time}`

    }
    fetchPost(url).then((res) => {
      if (res.code === 0) {

        this.setState({
          repaymentInfo: res.data.repaymentInfo,
          visible: true
          // startDt: res.data.repaymentInfo.startDt
        })

      } else {
        message.error(res.msg)
      }
    })
  }

  handleOk() {
    this.setState({
      paidCapital: 0,
      discountCapital: 0,
    })
    let self = this
    if (this.state.repaymentInfo.billStatus === 2) {
      this.setState({
        visible: !this.state.visible,
      }, () => {
        self.getData()
      })
    } else {
      this.props.form.validateFields((error) => {
        if (!error) {
          let data = this.props.form.getFieldsValue()
          data.happenedAt = data.happenedAt.format('YYYY-MM-DD HH:mm:ss')
          fetchPost(`/liquidation/${this.state.repaymentInfo.billNo}/repay`, data).then((res) => {
            if (res.code === 0) {
              self.props.form.resetFields()
              this.setState({
                visible: !this.state.visible
              }, () => {
                self.getData()
              })
            } else {
              message.error(res.msg)
            }
          })
        }
      })
    }
  }

  handleCancel() {
    this.setState({
      visible: !this.state.visible,
      paidCapital: 0,
      discountCapital: 0,
    })
  }

  handleChangeTime(moment) {
    let time = moment.format('YYYY-MM-DD')
    this.getPaybackItem('', time)
  }

  /**
   * 展示还款信息
   */
  showRepaymentInfo() {
    //已经结清
    if (this.state.repaymentInfo.billStatus === 2) {
      return (<div>
        <p className='font14 mt10'>Repayment Channel: {this.state.repaymentInfo.repaymentChannel}</p>
        <p className='font14 mt10'>Transaction Number: {this.state.repaymentInfo.transactionNumber}</p>
        <p className='font14 mt10'>Repayment Date: {this.state.repaymentInfo.repaymentDate}</p>
      </div>)

    } else {
      const {getFieldDecorator} = this.props.form
      return (<div>
        <FormItem labelCol={{span: 10}}
                  wrapperCol={{span: 10}} label='Repayment Date:'>
          {
            getFieldDecorator('happenedAt', {rules: [{required: true}]})(
              <DatePicker onChange={(e) => {
                this.handleChangeTime(e)
              }} disabledDate={this.disabledStartDate}/>
            )
          }
        </FormItem>
        <FormItem className='mt20' labelCol={{span: 10}}
                  wrapperCol={{span: 10}} label='Repayment Amount:'>
          {
            getFieldDecorator('paidCapital', {
              rules: [{
                required: true,
                message: 'Please enter the amount of repayment'
              }, {pattern: /^[0-9]*\.?[0-9]{0,2}$/, message: 'Please enter the correct format'}]
            })(
              <Input type='text' value={this.state.paidCapital} onChange={(event) => this.paidCapitalChange(event)}/>
            )
          }
        </FormItem>
        <FormItem className='mt20' labelCol={{span: 10}}
                  wrapperCol={{span: 10}} label='Deductible Amount:'>
          {
            getFieldDecorator('discountCapital', {
              rules: [{
                message: 'Please enter the amount of repayment'
              }, {pattern: /^[0-9]*\.?[0-9]{0,2}$/, message: 'Please enter the correct format'}]
            })(
              <Input type='text' value={this.state.discountCapital}
                // disabled={this.state.repaymentInfo.overdueDays <= 30}
                     onChange={(event) => this.discountCapitalChange(event)}/>
            )
          }
        </FormItem>
        {/*<FormItem className='mt20' labelCol={{span: 10}}*/}
        {/*wrapperCol={{span: 10}} label='Repayment Channel:'>*/}
        {/*{*/}
        {/*getFieldDecorator('payChannel', {*/}
        {/*rules: [{*/}
        {/*required: true,*/}
        {/*message: 'Please enter the channel of repayment'*/}
        {/*}]*/}
        {/*})(*/}
        {/*<Input type='text'/>*/}
        {/*)*/}
        {/*}*/}
        {/*</FormItem>*/}
        <FormItem className='mt20' labelCol={{span: 10}}
                  wrapperCol={{span: 10}} label='Transaction Number:'>
          {
            getFieldDecorator('tripleNo', {
              rules: [{
                required: true,
                message: 'Please enter the txnId of repayment'
              }]
            })(
              <Input type='text'/>
            )
          }
        </FormItem>

      </div>)
    }
  }

  paidCapitalChange(event) {
    this.setState({paidCapital: event.target.value})
  }

  discountCapitalChange(event) {
    this.setState({discountCapital: event.target.value})
  }

  /**
   * 导出资方数据
   */
  exportFundData() {
    this.setState({
      buttonHidden: true
    })
    let copyState = {}
    for (let i in this.state.params) {
      if (this.state.params[i] != '') {
        copyState[i] = this.state.params[i]
      }
    }
    if (!copyState.lowerReceivedDate) {
      copyState.lowerReceivedDate = moment().subtract('days', 1).format('YYYY-MM-DD')
    }
    if (!copyState.upperReceivedDate) {
      copyState.upperReceivedDate = moment().subtract('days', 1).format('YYYY-MM-DD')
    }
    if (!copyState.orderType) {
      copyState.orderType = '0'
    }

    exportFile('/finance/fund/data/list/export', `data-${moment().format('YYYY-MM-DD')}.xlsx`, copyState).then(json => {
      this.setState({
        buttonHidden: false
      })
    })
    message.info("Downloading please wait")
  }

  render() {
    const self = this
    const {getFieldDecorator} = this.props.form
    return (
      <div>

        <Modal visible={this.state.visible} okText={this.state.repaymentInfo.billStatus === 2 ? 'ok' : 'repayment'}
               onOk={() => {
                 this.handleOk()
               }} onCancel={() => {
          this.handleCancel()
        }}>
          <Form className={Styles.formWrapper}>
            <div className={Styles.info}>
              <div className={Styles.wrapper}>
                <Col span={24} className='font14 mt10'>
                  Loan ID:{this.state.repaymentInfo.orderNo}
                </Col>
                <Row gutter={8}>
                  <Col span={12} className='font14 mt10'> Repayment
                    Amount: {this.state.repaymentInfo.repaymentCapital}</Col>
                  <Col span={12} className='font14 mt10'> Loan Amount: {this.state.repaymentInfo.borrowCapital}</Col>
                </Row>
                <Row gutter={8}>
                  <Col span={12} className='font14 mt10'> Deductible
                    Amount: {this.state.repaymentInfo.discountCapital}</Col>
                  <Col span={12} className='font14 mt10'> Tenure: {this.state.repaymentInfo.periodLength}Days</Col>
                </Row>
                <Row gutter={8}>
                  <Col span={12} className='font14 mt10'> Overdue
                    Days: {this.state.repaymentInfo.overdueDays}Days</Col>
                  <Col span={12} className='font14 mt10'> Interest: {this.state.repaymentInfo.interest}</Col>
                </Row>
                <Row gutter={8}>
                  <Col span={12} className='font14 mt10'> Processing
                    Fee: {this.state.repaymentInfo.serviceFee}</Col>
                  <Col span={12} className='font14 mt10'> Overdue Service
                    Fee: {this.state.repaymentInfo.overdueServiceFee}</Col>
                </Row>
                <Row gutter={8}>
                  <Col span={12} className='font14 mt10'> Total
                    Penalty: {this.state.repaymentInfo.overdueFee}</Col>
                  <Col span={12} className='font14 mt10'> Penalty Per
                    {/* TODO 之后后台获取罚息利率*/}
                    Day: {this.state.repaymentInfo.borrowCapital * 0.01}</Col>
                </Row>


                <Col span={24} className='font14 color-main mt10'>
                  Remaining Repayment
                  Amount:{(this.state.repaymentInfo.remainCapital - this.state.paidCapital - this.state.discountCapital) < 0 ? 0 : (this.state.repaymentInfo.remainCapital - this.state.paidCapital - this.state.discountCapital)}
                </Col>
              </div>
              {this.showRepaymentInfo()}

            </div>

          </Form>

        </Modal>


        <div className={searchStyle.searchClass}>
          <Search searchParams={this.state.searchParams} changeParams={(params) => this.changeParams(params)}
                  showAllReview={this.state.showAllReview}/>
        </div>

        <Table style={{marginTop: '20px'}} pagination={false} size='small' dataSource={this.state.list}
               loading={this.state.loading}
               bordered
               scroll={{x: 1700}}
        >
          <Column
            title='Loan ID'
            dataIndex='orderId'
            key='orderId'
            width='150'
          />
          <Column
            title='Name'
            dataIndex='userName'
            key='userName'
            width='250'
          />
          <Column
            title='Mobile'
            dataIndex='mobile'
            key='mobile'
            width='120'
          />
          <Column
            title='Email'
            dataIndex='email'
            key='email'
            width='150'
          />
          <Column
            title='Loan Amount/Tenure'
            dataIndex='loanAmountAndTenure'
            key='loanAmountAndTenure'
            render={(text, record) => {
              return `${record.loanAmount}/${record.periodLength}`
            }}
            width='150'
          />
          <Column
            title='Disburse Amount'
            dataIndex='amountYouGet'
            key='amountYouGet'
            width='120'
          />
          <Column
            title='Transfer Date'
            dataIndex='transferCompletedTime'
            key='transferCompletedTime'
            width='150'
          />
          <Column
            title='Planned repayment time'
            dataIndex='plannedRepaymentTime'
            key='plannedRepaymentTime'
            render={(text, record) => {
              return moment(record.plannedRepaymentTime).format('YYYY-MM-DD')
            }}
            width='180'
          />
          <Column
            title='Actual repayment time'
            dataIndex='actualRepaymentTime'
            key='actualRepaymentTime'
            width='150'
          />
          <Column
            title='Gateway serial number'
            dataIndex='gatewaySerialNumber'
            key='gatewaySerialNumber'
            width='180'
          />
          <Column
            title='Settlement Amount'
            dataIndex='settlementAmount'
            key='settlementAmount'
            width='120'
          />

        </Table>
        <Pagination style={{marginTop: '20px'}}
                    current={self.state.page.currentPage}
                    total={self.state.page.totalCount || 0}
                    pageSize={self.state.page.pageSize || 0}
                    onChange={(current) => {
                      self.nextpage(current)
                    }}
                    showSizeChanger={false}
                    showQuickJumper
                    showTotal={(total) => `total ${total} items`}
        />

      </div>
    )
  }
}

Paid = Form.create()(Paid)
export default Paid
